#!/usr/bin/env bash

# Copyright Materialize, Inc. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software will be governed
# by the Apache License, Version 2.0.
#
# pre-push — sample Git hook to validate commits before pushing.
#
# To install this hook, copy or symlink it into .git/hooks/pre-push:
#
#     $ ln -s ../../misc/githooks/pre-push .git/hooks/pre-push
#

set -euo pipefail

. misc/shlib/shlib.bash

# We declare some unused variables here to make it clear what fields
# are provided to us as input.
# shellcheck disable=SC2034
while read -r local_ref local_sha remote_ref remote_sha; do
    oldlist=$(git stash list)
    git stash save --quiet --include-untracked
    newlist=$(git stash list)
    oldref=$(git symbolic-ref --quiet HEAD)
    if [[ -z "$oldref" ]]; then
        oldref=$(git rev-parse HEAD)
    fi
    git checkout --quiet "$local_sha"
    reset() {
        if [[ "$oldlist" != "$newlist" ]]; then
            git stash pop --quiet --index || true
        fi
        if [[ "$oldref" != "$local_sha" ]]; then
            git checkout --quiet -
        fi
    }
    trap reset EXIT
    bin/pre-push
done
